package com.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.util.Log;
import com.example.myapplication.R;
import com.news.model.News;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

public class NewsAdapter extends ArrayAdapter<News> {

    private Context context;

    public NewsAdapter(Context context, List<News> newsList) {
        super(context, 0, newsList);
        this.context = context;
    }


    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // Get the data item for this position
        News news = getItem(position);
        // Check if an existing view is being reused, otherwise inflate the view
        if (convertView == null) {
            convertView = LayoutInflater.from(context).inflate(R.layout.news_item, parent, false);
        }

        // 初始化新闻信息控件
        ImageView imageView = convertView.findViewById(R.id.imageUrl);
        TextView titleTextView = convertView.findViewById(R.id.news_title);
        TextView timeTextView = convertView.findViewById(R.id.news_time);
        TextView id = convertView.findViewById(R.id.news_author);

        // Populate the data into the template view using the data object
        imageView.setImageResource(R.mipmap.box);
        titleTextView.setText(news.getTitle());
        id.setText(String.valueOf(news.getAuthor()));
        // 将长整型时间戳转换为可读的日期时间字符串
        long publishedAt = news.getPublishedAt();
        Log.e("时间戳", String.valueOf(publishedAt));
        String formattedDate = formatDate(publishedAt);
        timeTextView.setText(formattedDate);

        // Return the completed view to render on screen
        return convertView;
    }
    private String formatDate(long time) {
        Date date = new Date(time ); // 假设时间戳是秒级单位，需要转换为毫秒级
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
        return sdf.format(date);
    }
}
